package com.sky.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
@ServerEndpoint("/ws/{sid}")    //标识当前类就是处理websocket请求
public class WebSocketServer {

    private static Map<String, Session> sessionMap = new HashMap<>();   // 所有与服务器建立连接的会话对象

    @OnOpen // 该方法连接建立时触发
    public void open(Session session, @PathParam("sid") String sid){
        log.info("连接建立, {}", sid);
        sessionMap.put(sid, session);
    }

    @OnMessage // 该方法是接收到客户端发送过来的消息时触发
    public void onMessage(Session session, String message ,@PathParam("sid") String sid){
        log.info("接收到消息, {}", message);
    }

    @OnClose // 该方法是关闭连接时触发
    public void onClose(Session session, @PathParam("sid") String sid){
        log.info("关闭连接");
        sessionMap.remove(sid);
    }

    @OnError // 通信异常时触发
    public void onError(Session session, @PathParam("sid") String sid, Throwable throwable){
        log.info("出异常了");
        throwable.printStackTrace();
    }

    /**
     * 广播消息
     */
    public void sendMessageToAllClient(String message) throws IOException {
        Collection<Session> sessions = sessionMap.values();
        if (!CollectionUtils.isEmpty(sessions)){
            for (Session session : sessions) {
                // 发送消息
                session.getBasicRemote().sendText(message);
            }
        }
    }
}
